import {Component, OnInit} from '@angular/core';
import {TipService} from "../../services/tip.service";
import {ExtendHttpService} from "../../../common/extend-http.service";
import {Router} from "@angular/router";
@Component({
  selector: 'app-change-pwd',
  templateUrl: './change-pwd.component.html',
  styleUrls: ['./change-pwd.component.css']
})
export class ChangePwdComponent implements OnInit {

  isLoading = false;
  tipType = 'error';
  submitType = true;

  pwd = {
    oldPwd: '',
    newPwd: '',
    newPwd1: ''
  }

  constructor(private tipService: TipService,
              private extendHttp: ExtendHttpService,
              private router: Router,) {
  }

  ngOnInit() {
    cBack = () => {
      $('#btn-back').trigger('click');
    }
  }

  submitData() {
    if (!this.isLoading) {
      if (!this.pwd.oldPwd.trim()) {
        this.tipType = 'error';
        this.tipService.change(true, '请输入原密码');
        return;
      }

      if (!this.pwd.newPwd.trim()) {
        this.tipType = 'error';
        this.tipService.change(true, '请输入新密码');
        return;
      }

      if (!this.pwd.newPwd1.trim()) {
        this.tipType = 'error';
        this.tipService.change(true, '请再次输入新密码');
        return;
      }

      if (this.pwd.newPwd != this.pwd.newPwd1.trim()) {
        this.tipType = 'error';
        this.tipService.change(true, '两次输入新密码不一致');
        return;
      }

      this.isLoading = !this.isLoading;
      this.extendHttp.post('/merchantApp/basics/loginInfo/changePwd', {
        oldPwd: hex_md5(this.pwd.oldPwd),
        newPwd: hex_md5(this.pwd.newPwd)
      }).subscribe(response => {
        let data = response.json();
        if (data.code == '0') {
          this.submitType = false;
          this.isLoading = !this.isLoading;
          this.tipType = 'success';
          this.submitType = false;
          this.tipService.change(true, '修改成功,请重新登录');
        } else if (data.code == '-2001') {
          this.tipType = 'error';
          this.tipService.change(true, '登录超时，跳转到登录页面');
          setTimeout(() => {
            this.router.navigate(['/login']);
          }, 2000);
        } else {
          this.tipType = 'error';
          this.tipService.change(true, data.message);
          this.isLoading = !this.isLoading;
        }
      }, error => {
        this.tipType = 'error';
        this.tipService.change(true, '系统繁忙，操作失败！');
        this.isLoading = !this.isLoading;
      });
    }
  }
}
